<template>
    <div  class="payRecord">

        <div class="container">
            <div class="handle-box">
                <el-button type="success" size="mini" icon="el-icon-plus" @click="handleAdd" class="mr10">新增</el-button>
            </div>

            <el-table

                    :data="tableData"
                    height="300px"
                    border
                    class="table tables"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column prop="paid" width="150" label="支付金额"  align="center"></el-table-column>
                <el-table-column label="支付时间" align="center" width="180">
                    <template slot-scope="scope">{{ scope.row.payTime | formatDate}}</template>
                </el-table-column>
                <el-table-column prop="remark" label="备注"  align="center"></el-table-column>
                <el-table-column label="操作" width="300" align="center"  fixed="right">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="success"
                                icon="el-icon-view"
                                @click="handleview(scope.$index, scope.row)"
                        >查看</el-button>
                        <el-button
                                size="mini"
                                type="success"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="danger"
                                icon="el-icon-delete"
                                size="mini"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="params.page"
                        :page-size="params.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>

        </div>

        <!-- 新增/编辑-弹出框 -->
        <el-dialog :title="dialogStatus" :visible.sync="addVisible" width="70%"  append-to-body>
            <el-form  ref="ruleForm"  label-width="120px" :model="payRecordData" :rules="rules">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="付款金额" prop="paid">
                            <el-input v-model.number="payRecordData.paid"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="付款时间" prop="payTime">
                           <!-- <el-date-picker
                             v-model="payRecordData.payTime"
                             type="datetime"
                             placeholder="选择日期时间">
                            </el-date-picker> -->
                            <!-- <el-date-picker
                                    v-model="payRecordData.payTime"
                                    type="datetime"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%;"></el-date-picker> -->
                            <el-date-picker
                                    v-model="payRecordData.payTime"
                                    type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注">
                            <el-input v-model.number="payRecordData.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-upload
                            ref="upload"
                            class="import-btn"
                            :action="serverSrc+'/contractpay/upload'"
                            name="upfile"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :before-remove="handleRemove"
                            :beforeUpload="beforeAvatarUpload"
                            
                            :headers="myHeaders"
                            :on-success="uploadSuccess"
                            :on-error="uploadError"
                            accept="image/gif, image/jpeg, image/jpg, image/png, image/svg"
                            :show-file-list="true"
                            :file-list="fileList"
                    >   <!-- :data='query'    :on-remove="handleRemove"-->  
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible" append-to-body>
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="paySubmitForm('ruleForm')" type="primary" size="small" :loading="isLogin">确定</el-button>
            </span>
        </el-dialog>

        <!-- 查看图片-弹出框 -->
        <el-dialog title="图片" :visible.sync="viewVisible" width="70%"  append-to-body>
            <div style="display:inline-block;margin-left:10px" v-for="(item,index) in imageList" :key="index">
                <el-image
                        style="width: 100px; height: 100px"
                        :preview-src-list="imageList"
                        :src="item"></el-image>
            </div>
            <p style="text-align:center" v-if="imageList.length == 0">暂无数据</p>
        </el-dialog>

    </div>
</template>
<script>
    export default {
        name: 'payRecord',
        data() {
            var  validateNumber= (rule, value, callback) => {
                if(value > this.contractIdContent.totalSum){
                    callback(new Error('付款金额必须小于合同总金额!'));
                }else{
                    callback();
                }
            };
            return {
               loading: true,
               isLogin:false,
               payRecordData:{},
               addVisible:false,
               dialogStatus:'',
               rules:{
                   paid:[
                        { required: true, message: '请输入合同总金额', trigger: 'blur' },
                        { type: 'number', message: '合同总金额必须为数字值'},
                          {validator:validateNumber ,trigger: 'blur'}],
                   payTime: [ { required: true, message: '请选择付款时间', trigger: 'change' }]
              },
              params:{
                page:1,
                pageSize:10
              },
                pageTotal:0,
                tableData:[],
              //图片上传
                myHeaders:{
                    'SYSPLATFORMCOOKIE':localStorage.getItem('bixsyscookie')
                },
                fileList: [],
                dialogVisible: false,
                picId:'',
                dialogImageUrl: '',
                type:1,
                contractIdContent:{},
                //查看图片
                viewVisible:false,
                imageList:[],
                imageUrl:'',
            }
        },
        filters: {
            formatDate: function (timestamp) {
                var date = new Date(timestamp * 1000);
                var Y = date.getFullYear() + '-';
                var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                var D = date.getDate() + ' ';
                var h = date.getHours() + ':';
                var m = date.getMinutes() + ':';
                var s = date.getSeconds();
                return Y + M + D + h + m + s;
            }
        },
        create(){

        },
        methods: {
            beforeAvatarUpload(file) {          
                const isLt2M = file.size / 1024 / 1024 < 0.5   
                if(!isLt2M) {  
                    this.$message({  
                        message: '当前图片过大，请上传小于500k图片',  
                        type: 'warning'  
                    });  
                } 
                return isLt2M  
            } ,  
            //图片上传
            paySubmitForm(formName) {
                var _this=this;
                this.payRecordData.picId=this.picId;
                let url= this.type ==1 ? '/contractpay/create' : '/contractpay/update';
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.isLogin = true;
                        this.$axios.post(url, this.payRecordData)
                            .then((res) => {
                                if(res.code!=200){
                                    setTimeout(() =>{
                                        this.isLogin = false;
                                        this.$message.error(`${res.message}`);
                                    }, 0.1 * 1000 );
                                }else{
                                    setTimeout(() =>{
                                        this.isLogin = false;
                                        this.$message.success(`${res.message}`);
                                        this.addVisible = false;
                                        this.getchildDataMore(this.contractIdContent)
                                        if(this.fileList.length != 0){
                                            this.$refs.upload.clearFiles();
                                        }
                                    }, 0.1 * 1000 );
                                }
                            })
                            .catch(() => {
                                this.isLogin = false;
                            });
                    }
                });
            },
            handleRemove(file, fileList) {
                let id= file.response ? file.response.data.id : file.id;
                this.$axios.get('/file/delete',{
                    params:{
                        'id':id
                    }
                })
                    .then((res) => {
                        if(res.code == "200"){
                            this.picId=this.picId.replace(id+',', '');
                            console.log('del',this.picId);
                            this.$message.success('删除成功');
                        }
                    })
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${ file.name }？`);
            },
            uploadSuccess(response,file, fileList){
                this.fileList=fileList;
                this.picId+= response.data.id + ',';
                this.$message.success('图片上传成功');
            },
            uploadError(file, fileList){
                this.$message.error('图片上传失败');
            },
            handlePictureCardPreview(file, fileList) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            //获取图片列表
            getImgPicture(id){
                let params={
                    'relationId': id,
                    'type':'pay'
                }
                this.$axios.post('/file/getPicList', params)
                    .then(response => {
                        this.fileList=response.data;
                        response.data.map( item =>{
                            this.imageList.push(item.url);
                            this.picId = item.id + "," + this.picId;
                        })
                        this.imageUrl=this.imageList[0];
                    }).catch(error => {
                    console.log(error);
                })
            },
            //查看页面弹窗
            handleview(index, row){
                this.viewVisible=true;
                this.picId='';
                this.imageList=[];
                this.imageUrl='';
                this.getImgPicture(row.id)
            },
            handleAdd(){
                if( this.fileList.length != 0){
                    this.$refs.upload.clearFiles();
                    this.fileList=[]
                }
               this.picId='';
               this.addVisible=true;
               this.type=1;
               this.dialogStatus="新增";
               this.payRecordData={
                        contractId:this.contractIdContent.id,
                        paid:'',
                        payTime:'',
                        remark:'',
                        picId:''
                }
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.params, 'page', val);
                this.getchildDataMore(this.contractIdContent)
            },
            getchildDataMore(val){
                var _this=this;
                this.params.contractId=val.id;
                this.contractIdContent=val;
                this.$axios.post('/contractpay/selectPages', this.params)
                    .then((res) => {
                            this.tableData=res.data.results;
                            this.pageTotal = res.data.count;

                    })
                    .catch(() => {
                        console.log('error submit!!');
                        return false;
                    });
            },
            handleDelete(index, row) {
                let params={
                    'contractId':this.contractIdContent.id,
                    'ids':row.id
                }
                this.$axios.post('/contractpay/delete', params)
                    .then((res) => {
                        if(res.code == "200"){
                            this.$message.success('删除成功');
                            this.getchildDataMore(this.contractIdContent)
                        }else{
                            this.$message.error('删除失败');
                        }

                    })
                    .catch(() => {
                        console.log('error submit!!');
                        return false;
                    });
            },
   
            handleEdit(index, row) {
                console.log(formatDate(row.payTime));

                this.dialogStatus = '编辑';
                this.picId='';
                this.addVisible=true;
                this.type=0;
                this.payRecordData={
                    id:row.id,
                    contractId:this.contractIdContent.id,
                    paid:row.paid,
                    payTime:new Date(formatDate(row.payTime)),
                    remark:row.remark,
                    picId:row.picId
                }
                this.getImgPicture(row.id)
            }
        },
        watch: {

        },
        mounted() {

        }
    }
    function formatDate(timestamp) {
         var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	    var Y = date.getFullYear() + '-';
	    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	    var D = date.getDate() + ' ';
	    var h = date.getHours() + ':';
	    var m = date.getMinutes() + ':';
	    var s = date.getSeconds();
	    return Y + M + D + h + m + s;
    }
</script>

<style></style>

<style lang="scss" scoped></style>